/*   
 * Copyright 2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.beaconframework.vaadin.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.beaconframework.vaadin.util.VaadinContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.vaadin.Application;

public abstract class FeatureInjector implements Comparable<FeatureInjector>,
        ApplicationContextAware {

    int priority = 10;
    boolean enabled = true;
    ApplicationContext applicationContext;

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    public final Application getApplication() {
        return VaadinContext.getApplication();
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public abstract void inject();

    @Override
    public int compareTo(FeatureInjector o) {
        if (getPriority() > o.getPriority()) {
            return 1;
        } else if (getPriority() == o.getPriority()) {
            return 0;
        } else {
            return -1;
        }
    }

    public static void inject(ApplicationContext ctx) {
        List<FeatureInjector> contributors = new ArrayList<FeatureInjector>();
        contributors.addAll(ctx.getBeansOfType(FeatureInjector.class).values());
        Collections.sort(contributors);
        for (FeatureInjector fd : contributors) {

            if (fd.isEnabled()) {
                fd.inject();
            } else {
                // log
            }

        }
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

}
